{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List, Dict, Optional\n",
    "from datetime import date\n",
    "\n",
    "from pydantic import BaseModel\n",
    "\n",
    "# Declare a variable as a str\n",
    "# and get editor support inside the function\n",
    "def main(user_id: str):\n",
    "    return user_id\n",
    "\n",
    "\n",
    "# A Pydantic model\n",
    "class User(BaseModel):\n",
    "    id: int\n",
    "    name: str\n",
    "    joined: date\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "User(id=1, name='John Doe', joined=datetime.date(2018, 7, 19))"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_user: User = User(id=1, name=\"John Doe\", joined=\"2018-07-19\")\n",
    "my_user"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "my_user: User = User(id=3, name=\"John Doe\", joined=\"2018-07-19\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "User(id=3, name='John Doe', joined=datetime.date(2018, 7, 19))"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "second_user_data = {\n",
    "    \"id\": 4,\n",
    "    \"name\": \"Mary\",\n",
    "    \"joined\": \"2018-11-30\",\n",
    "}\n",
    "\n",
    "User(**second_user_data)\n",
    "my_user"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'id': 1, 'name': 'John Doe', 'joined': datetime.date(2018, 7, 19)}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_user = User(id=1, name=\"John Doe\", joined=\"2018-07-19\", aaaa='aaa')\n",
    "my_user.dict()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Spam(foo=Foo(count=4, size=None), bars=[Bar(apple='x1', banana='y'), Bar(apple='x2', banana='y')])"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from typing import List, Optional\n",
    "from pydantic import BaseModel\n",
    "\n",
    "\n",
    "class Foo(BaseModel):\n",
    "    count: int = ...\n",
    "    size: float = None\n",
    "\n",
    "\n",
    "class Bar(BaseModel):\n",
    "    apple = 'x'\n",
    "    banana = 'y'\n",
    "\n",
    "\n",
    "class Spam(BaseModel):\n",
    "    foo: Foo = ...\n",
    "    bars: List[Bar] = ...\n",
    "\n",
    "\n",
    "s = Spam(foo={'count': 4}, bars=[{'apple': 'x1'}, {'apple': 'x2'}])\n",
    "s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "s.dict()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 验证"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "name='Samuel Colvin' username='scolvin' password1='zxcvbn' password2='zxcvbn'\n"
     ]
    }
   ],
   "source": [
    "from pydantic import BaseModel, ValidationError, validator\n",
    "\n",
    "\n",
    "class UserModel(BaseModel):\n",
    "    name: str\n",
    "    username: str\n",
    "    password1: str\n",
    "    password2: str\n",
    "\n",
    "    @validator('name')\n",
    "    def name_must_contain_space(cls, v):\n",
    "        if ' ' not in v:\n",
    "            raise ValueError('must contain a space')\n",
    "        return v.title()\n",
    "\n",
    "    #联合验证\n",
    "    @validator('password2')\n",
    "    def passwords_match(cls, v, values, **kwargs):\n",
    "        if 'password1' in values and v != values['password1']:\n",
    "            raise ValueError('passwords do not match')\n",
    "        return v\n",
    "\n",
    "    @validator('username')\n",
    "    def username_alphanumeric(cls, v):\n",
    "        assert v.isalpha(), 'must be alphanumeric'\n",
    "        return v\n",
    "\n",
    "\n",
    "print(\n",
    "    UserModel(name='samuel colvin',\n",
    "              username='scolvin',\n",
    "              password1='zxcvbn',\n",
    "              password2='zxcvbn'))\n",
    "#> name='Samuel Colvin' username='scolvin' password1='zxcvbn' password2='zxcvbn'\n",
    "\n",
    "try:\n",
    "    UserModel(name='sam uel',\n",
    "              username='scolvin',\n",
    "              password1='zxcvbn',\n",
    "              password2='zxcvbn')\n",
    "except ValidationError as e:\n",
    "    print(e)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "231.6px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
